package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    /**
     * 分类分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        log.info("分类分页查询...");
        //构造分页条件构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //构造查询条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //设置查询条件
        queryWrapper.orderByAsc(Category::getSort);
        //调用方法查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}", category);
        if (categoryService.save(category)) {
            return R.success("添加成功");
        }
        return R.error("添加失败");

    }

    /**
     * 根据id删除分类
     * 判断当前分类是否关联菜品,套餐
     * 关联逻辑上不允许删除
     * 未关联可删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(long id) {
        log.info("删除分类,id为:{}", id);
//        categoryService.removeById(id);
        //调用service层根据id删除方法
        categoryService.remove(id);
        return R.success("删除分类成功");
    }

    /**
     * 修改菜品分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("打印修改信息:{}", category);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    @GetMapping("/list")//菜品管理  新建菜品 分类下拉框数据回显
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        queryWrapper.orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
